//
//  LeftPanelView.m
//  SocialEngine
//
//  Created by Tan NguyenBa on 9/10/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "LeftPanelView.h"
#import "LoginState.h"
#import "defines.h"

@implementation LeftPanelView {
    NSArray *arrPanelList;
    NSArray *arrPanelListImg;
    LoginState *loginState;
    NSInteger iCurrentView;
    
    UIImageView *userAvatar;
}

@synthesize delegate;
@synthesize searchBar;
@synthesize m_tableData;


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Default user avatar
        userAvatar = nil;
        
        [self setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0]];
        self.autoresizesSubviews = YES;
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        // Initialization code
        searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [self bounds].size.width, SEARCHBAR_HEIGHT)];
		searchBar.delegate = self;	
		// [searchBar sizeToFit];		
		searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
		searchBar.tintColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
		searchBar.backgroundColor = [UIColor clearColor];
		searchBar.opaque = YES;
        
        searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        // searchBar.autoresizesSubviews = YES;
        // searchBar.delaysContentTouches = NO;


        // self.tableData.tableHeaderView = m_searchBar;
		[self addSubview:searchBar];
        
        // m_tableData = [[UITableView alloc] init];
        m_tableData = [[UITableView alloc] initWithFrame:CGRectMake(0, SEARCHBAR_HEIGHT, [self bounds].size.width, [self bounds].size.height - SEARCHBAR_HEIGHT) style:UITableViewStylePlain];
        [m_tableData setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0]];
        m_tableData.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight;
        m_tableData.autoresizesSubviews = YES;
		m_tableData.dataSource = self; 
		m_tableData.delegate = self;
		[self addSubview:m_tableData];
        
        UISwipeGestureRecognizer *recognizerLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
		recognizerLeft.direction = UISwipeGestureRecognizerDirectionLeft;		
		[m_tableData addGestureRecognizer:recognizerLeft];
		        
        arrPanelList = [[NSArray alloc] initWithObjects:@"", @"Quick Links", @"What\'s new", @"My Messages", @"Friends", @"My Profile", @"Home", @"Member", @"Albums", @"Blogs", @"Classifields", @"Chat", @"Polls", @"Forum", @"Events", @"Groups", @"Music", @"Videos", nil];
        
        
        arrPanelListImg = [[NSArray alloc] initWithObjects:@"", @"quick_link.png", @"what_new.png", @"message.png", @"friend.png", @"my_profile.png", @"home.png", @"member.png", @"album.png", @"blog.png", @"classified.png", @"chat.png", @"poll.png", @"forum.png", @"event.png", @"group.png", @"music.png", @"video.png", nil];

    }
    return self;
}

- (void) handleSwipeFrom:(UISwipeGestureRecognizer *) recognizer
{
	[self.delegate closeLeftPanelView];
}

- (void) setLoginState:(LoginState *) _loginState {
    loginState = _loginState;
}

- (void) setCurrentView:(NSInteger) _iCurrentView {
    iCurrentView = _iCurrentView;
}

#pragma mark UISearchBarDelegate
- (void) searchBarTextDidBeginEditing:(UISearchBar *) theSearchBar {
    // ...
    searchBar.showsCancelButton = YES;
    [self.delegate openLeftPanelFullScreen];
}

- (void) searchBar:(UISearchBar *) theSearchBar textDidChange:(NSString *)searchText {
    // ...
}

- (void) searchBarSearchButtonClicked:(UISearchBar *) theSearchBar {
    // ...
}

- (void) searchBarCancelButtonClicked:(UISearchBar *) _searchBar
{
    [_searchBar resignFirstResponder];
    
    [self.delegate closeLeftPanelFullScreen];
    _searchBar.showsCancelButton = NO;
}


#pragma mark TableView delegate method

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Click Cell at index %d", indexPath.row);
   
    
    // Not include in searching mode
    // ...
    if (indexPath.row != 1) {
        // Not select Quick Link row
        //if (indexPath.row != iCurrentView) {
            [self.delegate changeFromView:iCurrentView toNewView:indexPath.row];
        //}
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
        return 58;
    else 
        return 42;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // NSLog(@"%d", [arrPanelListImg count]);
    return [arrPanelListImg count];
}

- (void) loadUserImage:(NSURL *)imageURL {
    NSOperationQueue *queue = [NSOperationQueue new];
    NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                        initWithTarget:self
                                        selector:@selector(requestRemoteImage:)
                                        object:imageURL];
    [queue addOperation:operation];
}

- (void)requestRemoteImage:(NSURL *) imageURL
{
    NSData *data = [NSData dataWithContentsOfURL:imageURL];
    [self performSelectorOnMainThread:@selector(placeImageInUI:) withObject:data waitUntilDone:YES];
}

- (void) placeImageInUI:(NSData *) imageData
{
    userAvatar.image = [UIImage imageWithData:imageData];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"panelCell"];
    
    //if (cell == nil) {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"panelCell"];
    // cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIView *bg = [[UIView alloc] initWithFrame:cell.frame];
    bg.backgroundColor = [UIColor blackColor];
    cell.backgroundView = bg;
    
    if (indexPath.row != 1) {
        UIView* bgSelected = [[UIView alloc] initWithFrame:cell.frame];
        // bgSelected.backgroundColor = [UIColor colorWithRed:140.0 green:140.0 blue:140.0 alpha:1.0];
        bgSelected.backgroundColor = [UIColor darkGrayColor];
        cell.selectedBackgroundView = bgSelected;
    }
    else {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    // NSLog(@"%d", indexPath.length);
    if ([indexPath row] > 0) {
        
        NSInteger leftMargin = 5;
        if (indexPath.row >= 2 && indexPath.row <= 5) {
            leftMargin = 40;
        }
        
        UIImageView * avatar = [[UIImageView alloc] initWithFrame:CGRectMake(leftMargin, 5, 32, 32)];
        avatar.image = [UIImage imageNamed:[arrPanelListImg objectAtIndex:[indexPath row]]];
        [cell.contentView addSubview:avatar];
        leftMargin += 40;
        
        
        UILabel *lbText = [[UILabel alloc] init];
        lbText.textAlignment = UITextAlignmentLeft;
        lbText.textColor = [UIColor whiteColor];	
        lbText.backgroundColor = [UIColor clearColor];
        lbText.text = [arrPanelList objectAtIndex:indexPath.row];
        lbText.frame = CGRectMake(leftMargin,
                                  0, 
                                  200,
                                  42);	
        
        [cell.contentView addSubview:lbText];
        
    }
    else {
        if (userAvatar == nil) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:loginState.strAvatarURL]];
            userAvatar = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 48, 48)];
            userAvatar.image = [UIImage imageWithData:data];
            // [self loadUserImage:[NSURL URLWithString:loginState.strAvatarURL]];
        }
        [cell.contentView addSubview:userAvatar];
                
        UILabel *lbText = [[UILabel alloc] init];
        lbText.textAlignment = UITextAlignmentLeft;
        lbText.textColor = [UIColor whiteColor];	
        lbText.font = [UIFont fontWithName:@"Arial" size:25];
        lbText.backgroundColor = [UIColor clearColor];
        lbText.text = loginState.strName;
        lbText.frame = CGRectMake(65,
                                  0, 
                                  200,
                                  58);	
        [cell.contentView addSubview:lbText];
    }
    //}
    
    return cell;
}

@end
